package com.bytebuddytest.fieldandmethod;

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy;
import org.junit.Assert;
import org.junit.Test;

import java.lang.reflect.Constructor;

/**
 * 超类方法调用
 *
 * @author yutianhong
 * @version 1.0
 * @since 2023/10/20 16:39
 */
@SuppressWarnings({"resource", "unused"})
public class SuperMethodCallTest {

    /*
     * ConstructorStrategy.Default.IMITATE_SUPER_TYPE
     * ConstructorStrategy.Default.NO_CONSTRUCTORS
     * ConstructorStrategy.Default.DEFAULT_CONSTRUCTOR
     */

    public static class Parent {
        public Parent(int i) {
            System.out.println("parent constructor: " + i);
        }
    }

    @Test
    public void testConstructorStrategy() {
        DynamicType.Builder<Parent> subclass = new ByteBuddy()
                .subclass(Parent.class, ConstructorStrategy.Default.DEFAULT_CONSTRUCTOR);
        try {
            subclass.make();
            Assert.fail();
        } catch (Throwable t) {
            Assert.assertTrue(t instanceof IllegalArgumentException);
        }
    }

    public static class Parent2 {
        public Parent2() {
            System.out.println("parent default constructor");
        }

        public Parent2(int i) {
            System.out.println("parent constructor with one argument: " + i);
        }
    }

    @Test
    public void testConstructorStrategy2() {
        Class<? extends Parent2> dynamicClazz = new ByteBuddy()
                .subclass(Parent2.class, ConstructorStrategy.Default.DEFAULT_CONSTRUCTOR)
                .make()
                .load(ClassLoader.getSystemClassLoader())
                .getLoaded();
        Constructor<?>[] constructors = dynamicClazz.getConstructors();
        for (Constructor<?> constructor : constructors) {
            System.out.println(constructor);
        }
        Assert.assertEquals(constructors.length, 1);
    }
}
